package ai;
import java.util.*;

import mapData.Coord;
import mapData.Map;
import mapData.Obstruction;
import mapObjects.Unit;

public class ComputerPlayer
{
    //AI will have access to both lists, but will only be able to manipulate compUnits 
    private ArrayList<Unit> plyrUnits;
    private ArrayList<Unit> compUnits; //AI will have access to both lists, but will only be able to manipulate this
    private ArrayList<Obstruction> obstrList; //AI should not modify contents of obstr
    private UnitGroup selectionGroup;
    private MapAnalyzer ma;
    int updateCount; //sets how often ho update AI
    Coord lastDest;
    
    public ComputerPlayer(ArrayList<Unit> player, ArrayList<Unit> comp, ArrayList<Obstruction> ob, UnitGroup u)
    {
	updateCount = 0;
        plyrUnits = player;
        compUnits = comp;
        obstrList = ob;
        selectionGroup = u;
        lastDest = null;
        ma = new MapAnalyzer(plyrUnits, compUnits); 
        
        
        for(int i = 0; i < compUnits.size(); i++)
        {
            selectionGroup.addUnit(compUnits.get(i));
        }
         
        //selectionGroup.setGroupDest(new Coord(10, 90));
        
    }
    
    public void update()
    {	
	if(updateCount == 0) 
    	{
	    
	    Coord c = getHighestDensityCenter();
	    if(lastDest == null || (Math.abs(lastDest.getX()-c.getX()) > 6 
		    || Math.abs(lastDest.getY() - c.getY()) > 6))
	    {
		selectionGroup.setGroupDest(c);
		lastDest = c;
	    	System.out.println("AI dest "+c);
	    }
    	}
	else
	{
	    ++updateCount;
	    if(updateCount == 20000000)
	    {
		updateCount = 0;
	    }
	}
    }
    //gets the highest density center. returns null if all 0
    private Coord getHighestDensityCenter() {
	ArrayList<Coord> centerList = new ArrayList<Coord>();
	for(int i = 0; i < Map.width; i+= Map.width/3)
	{
	    for(int j = 0; j < Map.height; j+= Map.height/3)
	    {
		centerList.add(ma.findHighestDensity(1, i, j, Map.width/3, Map.height/3));
		
	    }
	}
	Coord best = null;
	if(centerList.size() > 0)
	{
	    int bestSoFar = 0;
	    for(Coord c: centerList)
	    {
		if(c.centerVal > bestSoFar)
		{
		    bestSoFar = c.centerVal;
		    best = c;
		}
	    }
	}
	return best;
	
    }
    
    
    
}  